import re
from rest_framework import serializers
from user.models import User
from django_redis import get_redis_connection


class UserSerializer(serializers.ModelSerializer):
    # 额外的字段验证需要显示指明
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow')
        # 对于模型类字段进行额外限制条件添加
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5,
                'error_message': {
                    'max_length': '名字过长',
                    'min_length': '名字过短'
                }
            },
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
                'error_message': {
                    'max_length': '密码过长',
                    'min_length': '密码过短'
                }
            }
        }

        # 手机号验证
        def validata_mobile(self, value):
            if not re.match(r'^1[3-9]\d{9}$', value):
                return serializers.ValidationError('手机号码格式不正确')
            return value

        # 选中状态
        def validata_allow(self, value):
            if value != 'true':
                return serializers.ValidationError('协议未选择')
            return value

        def validata(self, attrs):
            # 密码判断
            if attrs['password'] != attrs['password2']:
                return serializers.ValidationError('密码输入不一致')

            # 短信验证
            conn = get_redis_connection('verify')
            sms_code_real = conn.get('sms_code_%s' % attrs['mobile'])
            if not sms_code_real:
                return serializers.ValidationError('验证码失效')

            if attrs['sms_code'] != sms_code_real.decode():
                return serializers.ValidationError('短信不一致')
            return attrs

        def create(self, validated_data):
            # 删除不需要保存的字段数据
            del validated_data['password2']
            del validated_data['sms_code']
            del validated_data['allow']

            user = super().create(validated_data)
            # 对于明文密码加密
            user.set_password(validated_data['password'])
            user.save()

            return user
